package com.amir.common.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;

import com.amir.common.api.download.DownloadHelper;
import com.amir.common.api.download.FileDownloadCallback;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import androidx.annotation.NonNull;

public class SavePicUtils {

    //    public static RequestOptions transform(){
//       return RequestOptions.bitmapTransform(new BlurTransformation(0,30));
//    }
    public static void url2Bitmap(Context context, String url, final Url2bitmapPicListener url2bitmapPicListener) {
        mUrl2bitmapPicListener = url2bitmapPicListener;
        //设置图片圆角角度
        RoundedCorners roundedCorners = new RoundedCorners(5);
        RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(300, 300);
        Glide.with(context).asBitmap().load(url).apply(options)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                        url2bitmapPicListener.transSucc(resource);
                    }
                });
    }

    public static void savePic(final Context context, Object url, SavePicListener savePicListener) {
        mSavePicListener = savePicListener;
        // 插入图库
        long time = new Date().getTime();
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/YaopaiDown";
        final File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }


        Glide.with(context).asFile().load(url).into(new SimpleTarget<File>() {
            @Override
            public void onResourceReady(File resource, Transition<? super File> transition) {
                try {
                    MediaStore.Images.Media.insertImage(context.getContentResolver(), resource.getAbsolutePath(), resource.getName(), resource.getName());
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                // 发送广播，通知刷新图库的显示
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + resource)));
                ToastUtil.Companion.show("保存成功");
                if (mSavePicListener != null) {
                    mSavePicListener.saveSuccess(resource);
                }
            }

        });
    }

    public static void saveBitmap(Bitmap bitmap, SavePicListener savePicListener) {
        Bitmap mBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        mSavePicListener = savePicListener;
        // 插入图库
        long time = new Date().getTime();
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/YaopaiDown";
        final File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        String fileUrl = file.getAbsolutePath() + "/" + time + ".jpg";
        try {
            FileOutputStream fos = new FileOutputStream(new File(fileUrl));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            if (mSavePicListener != null) {
                mSavePicListener.saveSuccess(new File(fileUrl));
            }
            fos.flush();
            fos.close();
            ToastUtil.Companion.show("保存成功，请到相册查看");

            Tools.INSTANCE.addMediaToLocalDb(Constant.getmContext(), fileUrl);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void downPic(final Context context, String url, SavePicListener savePicListener) {
        mSavePicListener = savePicListener;
        // 插入图库
        long time = new Date().getTime();
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/YaopaiDown";
        final File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }

        // 初始化
        DownloadHelper mDownloadHelper = new DownloadHelper();

        mDownloadHelper.downloadFile(url, file.getAbsolutePath(), time + ".jpg", new FileDownloadCallback<File>() {
            @Override
            public void onDownLoadSuccess(File file) {
                LogUtils.Companion.I(file.getAbsoluteFile());
                File absoluteFile = file.getAbsoluteFile();
                try {
//                    MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
                    // 发送广播，通知刷新图库的显示
                    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + absoluteFile)));
                    ToastUtil.Companion.show("保存成功");
                    mSavePicListener.saveSuccess(absoluteFile);
                } catch (Exception e) {
                    ToastUtil.Companion.show("保存失败");
                    e.printStackTrace();
                }
            }

            @Override
            public void onDownLoadFail(Throwable e) {
                ToastUtil.Companion.show("保存失败");
            }

            @Override
            public void onProgress(int progress, int total) {
                LogUtils.Companion.I(progress + ";" + total);
            }
        });
    }

    /**
     * 获取网络图片资源
     *
     * @param urlString
     * @return
     */
    public static void getHttpBitmap(final String urlString) {
        new Thread(() -> {
            HttpURLConnection connection = null;
            try {
                URL url = new URL(urlString);
                connection = (HttpURLConnection) url.openConnection();

                connection.setRequestMethod("GET");

                connection.setConnectTimeout(8000);
                connection.setReadTimeout(8000);
                Bitmap bitmap = null;
                final InputStream is = connection.getInputStream();
                if (is == null) {
                    throw new RuntimeException("stream is null");
                } else {
                    try {
                        byte[] data = readStream(is);
                        if (data != null) {
                            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    is.close();
                }
//                    // 下面对获取到的输入流进行读取
//                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//                    StringBuilder response = new StringBuilder();
//                    String line;
//                    while ((line = reader.readLine()) != null) {
//                        response.append(line);
//                    }

                Message message = new Message();
                message.what = 1;
                // 将服务器返回的结果存放到Message中
                message.obj = bitmap;
                handler.sendMessage(message);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }).start();

    }

    @SuppressLint("HandlerLeak")
    static Handler handler = new Handler() {


        @Override
        public void handleMessage(@NonNull Message msg) {
            saveBitmap((Bitmap) msg.obj, null);
        }
    };

    /*
     * 得到图片字节流 数组大小
     * */
    public static byte[] readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }

    public interface SavePicListener {

        void saveSuccess(File file);
    }

    public interface Url2bitmapPicListener {

        void transSucc(Bitmap file);
    }


    private static SavePicListener mSavePicListener;
    private static Url2bitmapPicListener mUrl2bitmapPicListener;
}
